package com.project.netmodule.net;

import android.app.Activity;
import com.google.gson.Gson;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.utils.module.SharePerferenceUtil;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

/**
 * Created by Administrator on 2016/4/14.
 */
public class RequestTask {

    private Activity mActivity;
    private Gson gson ;
    private HashMap publicMap ;

    public RequestTask(Activity activity) {
        mActivity = activity;
        gson = new Gson();
    }

    public void publicParameter(HashMap map){
        publicMap = map ;
    }

    public void execute(final String url, HashMap map, final String tag, final OnNetCallBack callBackListener) {

        try {
            map.putAll(publicMap);

            OkHttpClient mOkHttpClient = new OkHttpClient();

            SSLContext sc = null;
            sc = SSLContext.getInstance("SSL");
            sc.init(null, new TrustManager[]{new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }}, new SecureRandom());
            mOkHttpClient.setSslSocketFactory(sc.getSocketFactory());
            mOkHttpClient.setHostnameVerifier(new HostnameVerifier() {
                @Override
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            });
            FormEncodingBuilder builder = initBuilder(map);
            //创建一个Request
            Request request = new Request.Builder()
                    .url(url)
                    .post(builder.build())
                    .build();
            //new call
            Call call = mOkHttpClient.newCall(request);
            //请求加入调度
            call.enqueue(new Callback() {
                @Override
                public void onFailure(final Request request, IOException e) {
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
//                                String cache = SharePerferenceUtil.getVaule(mActivity, "NetDataCache", tag);
                                callBackListener.afterConnectFail(tag, null, "");
                            } catch (JSONException e1) {
                                e1.printStackTrace();
                            }
                        }
                    });
                }

                @Override
                public void onResponse(final Response response) throws IOException {
                    final String str = response.body().string();
                    mActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (response == null) {
//                                    String cache = SharePerferenceUtil.getVaule(mActivity, "NetDataCache", tag);
                                    callBackListener.afterConnectFail(tag, null, "");
                                } else {
                                    JSONObject obj = new JSONObject(str);
                                    if (200 == obj.optInt("code")) {
//                                        SharePerferenceUtil.saveValue(mActivity, "NetDataCache", tag, obj.toString());//网络文件存在SharePerference里
                                        callBackListener.afterConnectSuccess(tag, obj);
                                    } else {
//                                        String cache = SharePerferenceUtil.getVaule(mActivity, "NetDataCache", tag);
                                        callBackListener.afterConnectFail(tag, obj, "");
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    private FormEncodingBuilder initBuilder(HashMap<String, String> map) {
        FormEncodingBuilder builder = new FormEncodingBuilder();
//        try {
//            StringBuffer stringBuffer = new StringBuffer();   //存储封装好的请求体信息
//            stringBuffer.append("{");
//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                stringBuffer.append(entry.getKey())
//                        .append(":")
//                        .append("\""+URLEncoder.encode(entry.getValue(), "UTF-8")+"\"")
//                        .append(",");
//            }
//            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
//            stringBuffer.append("}");
//            builder.add("json", stringBuffer.toString());
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
//        return builder;
//        try {
//            builder.add("json", URLEncoder.encode(gson.toJson(map), "UTF-8"));
            builder.add("json", gson.toJson(map));
//        } catch (UnsupportedEncodingException e) {
//            e.printStackTrace();
//        }
        return builder;
    }

//    @Override
//    protected String doInBackground(Object[] params) {
//        return submitPostData(url, map, "UTF-8");
//    }
//
//    @Override
//    protected void onPostExecute(String str) {
//        try {
//            if ("-1".equals(str)) {
//                callBackListener.afterConnectFail(tag, null);
//            } else {
//                JSONObject obj = new JSONObject(str);
//                int resultCode = obj.optInt("code");
//                if (resultCode == 200) {
//                    callBackListener.afterConnectSuccess(tag, obj);
//                } else {
//                    callBackListener.afterConnectFail(tag, obj);
//                }
//            }
//        } catch (JSONException e) {
//            e.printStackTrace();
//        }
//    }
//
//    /*
//     * Function  :   发送Post请求到服务器
//     * Param     :   params请求体内容，encode编码格式
//     */
//    public String submitPostData(String strUrlPath, Map<String, String> params, String encode) {
//        //创建okHttpClient对象
//
//        return "-1";
//    }
//
//    /*
//     * Function  :   封装请求体信息
//     * Param     :   params请求体内容，encode编码格式
//     */
//    public String getRequestData(Map<String, String> params, String encode) {
//        String body = "";
//        StringBuffer stringBuffer = new StringBuffer();   //存储封装好的请求体信息
//        stringBuffer.append("{");
//        try {
//            for (Map.Entry<String, String> entry : params.entrySet()) {
//                stringBuffer.append(entry.getKey())
//                        .append(":")
//                        .append(URLEncoder.encode(entry.getValue(), encode))
//                        .append(",");
//            }
//            stringBuffer.deleteCharAt(stringBuffer.length() - 1);    //删除最后的一个"&"
//            stringBuffer.append("}");
//            body = "{json:" + stringBuffer.toString() + "}";
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return body;
//    }
//
//    /*
//     * Function  :   处理服务器的响应结果（将输入流转化成字符串）
//     * Param     :   inputStream服务器的响应输入流
//     */
//    public String dealResponseResult(InputStream inputStream) {
//        String resultData = null;      //存储处理结果
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
//        byte[] data = new byte[1024];
//        int len = 0;
//        try {
//            while ((len = inputStream.read(data)) != -1) {
//                byteArrayOutputStream.write(data, 0, len);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        resultData = new String(byteArrayOutputStream.toByteArray());
//        return resultData;
//    }

}
